import axios from 'axios';
import { mockCars, mockDealers, mockUsers, mockChatMessages } from './mockData';

// API base URL - change this to match your SpringBoot backend
const API_URL = 'http://localhost:8080/api';

// Flag to use mock data (set to false when backend is ready)
const USE_MOCK_DATA = true;

// Create axios instance with default config
const apiClient = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true
});

// Add request interceptor for auth token
apiClient.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

export default {
  // User authentication
  async login(username, password) {
    if (USE_MOCK_DATA) {
      // Simple mock login (in real app, validate credentials)
      const user = mockUsers.find(u => u.username === username);
      
      if (user && password) { // Simple validation - any non-empty password
        // Store token in localStorage for future requests
        localStorage.setItem('token', user.token);
        return user;
      } else {
        throw new Error('Invalid credentials');
      }
    }
    
    try {
      const response = await apiClient.post('/auth/login', { username, password });
      return response.data;
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  },
  
  // Get car details
  async getCars() {
    if (USE_MOCK_DATA) {
      // Return mock car data
      return mockCars;
    }
    
    try {
      const response = await apiClient.get('/cars');
      return response.data;
    } catch (error) {
      console.error('Error fetching cars:', error);
      throw error;
    }
  },
  
  async getCarDetails(carId) {
    if (USE_MOCK_DATA) {
      // Find car by ID in mock data
      const car = mockCars.find(c => c.car_id === carId);
      if (car) {
        return car;
      }
      throw new Error('Car not found');
    }
    
    try {
      const response = await apiClient.get(`/cars/${carId}`);
      return response.data;
    } catch (error) {
      console.error(`Error fetching car ${carId}:`, error);
      throw error;
    }
  },
  
  // Get dealer information
  async getDealers() {
    if (USE_MOCK_DATA) {
      // Return mock dealer data
      return mockDealers;
    }
    
    try {
      const response = await apiClient.get('/dealers');
      return response.data;
    } catch (error) {
      console.error('Error fetching dealers:', error);
      throw error;
    }
  },
  
  async getDealerDetails(dealerId) {
    if (USE_MOCK_DATA) {
      // Find dealer by ID in mock data
      const dealer = mockDealers.find(d => d.dealer_id === dealerId);
      if (dealer) {
        return dealer;
      }
      throw new Error('Dealer not found');
    }
    
    try {
      const response = await apiClient.get(`/dealers/${dealerId}`);
      return response.data;
    } catch (error) {
      console.error(`Error fetching dealer ${dealerId}:`, error);
      throw error;
    }
  },
  
  // Send chat message to dealer
  async sendDealerMessage(dealerId, message) {
    if (USE_MOCK_DATA) {
      // In mock mode, this would be handled by the socket service
      return { success: true };
    }
    
    try {
      const response = await apiClient.post(`/dealers/${dealerId}/chat`, { message });
      return response.data;
    } catch (error) {
      console.error('Error sending dealer message:', error);
      throw error;
    }
  },
  
  // Schedule appointment
  async scheduleAppointment(carId, dealerId, appointmentTime) {
    if (USE_MOCK_DATA) {
      // Simulate successful appointment creation
      return { 
        appointment_id: Math.floor(Math.random() * 1000),
        car_id: carId,
        dealer_id: dealerId,
        appointment_time: appointmentTime,
        status: '0'
      };
    }
    
    try {
      const response = await apiClient.post('/appointments', {
        carId,
        dealerId,
        appointmentTime
      });
      return response.data;
    } catch (error) {
      console.error('Error scheduling appointment:', error);
      throw error;
    }
  }
}; 